<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="carts"
      tooltip-effect="dark"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        prop="createTime"
        label="时间"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="bookName"
        label="书名"
        width="180"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="amount" label="数量" width="180" align="center">
      </el-table-column>
      <el-table-column prop="price" label="价格" width="180" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="showDialogD(scope.row.id)" type="success" plain
            >购买</el-button
          >
          <!-- 下面这个dialog代表的是选择单独购买的 -->
          <el-dialog
            title="选择地址"
            :visible.sync="dialogVisibleD"
            width="30%"
          >
            <el-select v-model="addressId">
              <el-option
                v-for="item in address"
                :key="item.id"
                :label="item.detailedAddress"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handleBuy">确 定</el-button>
            </span>
          </el-dialog>

          <!-- 下面是单独删除的功能 -->

          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-popconfirm
            title="确认删除？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            @confirm="handleConfirm(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-button
        :disabled="multipleSelection.length == 0 ? true : false"
        @click="toggleSelection()"
        >取消选择</el-button
      >
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-popconfirm
        title="确认删除？"
        confirm-button-text="确定"
        cancel-button-text="取消"
        icon="el-icon-info"
        icon-color="red"
        @confirm="handleConfirmP"
      >
        <el-button
          :disabled="multipleSelection.length == 0 ? true : false"
          type="danger"
          slot="reference"
        >
          批量删除</el-button
        >
      </el-popconfirm>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-button
        :disabled="multipleSelection.length == 0 ? true : false"
        type="success"
        @click="showDialogP"
      >
        批量购买</el-button
      >
      <!-- 下面这个dialog代表的是选择批量购买的 -->
      <el-dialog title="选择地址" :visible.sync="dialogVisible" width="30%">
        <el-select v-model="addressId">
          <el-option
            v-for="item in address"
            :key="item.id"
            :label="item.detailedAddress"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleBuyP()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
  
<script>
import {
  getCartsById,
  deleteByIds,
  deleteById,
  buyByIds,
  buyById,
} from "@/api/cartMG";
import { getAddress } from "@/api/addressMG";
export default {
  name: "CartView",
  data() {
    return {
      cartId: "", //在表中单独点击购买会把id放在这儿
      dialogVisible: false, //地址选择栏默认关闭--批量购买才会显示这个
      dialogVisibleD: false, //地址选择栏默认关闭--单独购买才会显示这个
      carts: [],
      address: [], //地址信息，一进入这个页面就去获取这个用户的所有地址
      addressId: 1, //选择的地址id,默认为获取到的地址的第一个id
      multipleSelection: [], //购物车被选择之后id存放的地方，每一次发送批量删除后就要清空
    };
  },
  methods: {
    showDialogP() {
      //批量购买弹出的地址框
      if (this.address.length == 0) {
        this.dialogVisible = false;
        this.$message({
          type: "info",
          showClose: true,
          message: "先去添加地址吧",
        });
        return;
      }
      this.dialogVisible = true;
      // console.log(id)
    },
    showDialogD(id) {
      //这是单独购买弹出的地址框
      if (this.address.length == 0) {
        this.dialogVisibleD = false;
        this.$message({
          type: "info",
          showClose: true,
          message: "先去添加地址吧",
        });
        return;
      }
      this.cartId = id;
      this.dialogVisibleD = true;
      // console.log(id)
    },
    async handleBuy() {
      //单独购买
      // console.log(this.addressId,this.cartId);
      // 发送请求
      await buyById(this.addressId, this.cartId).then((res) => {
        if (res.data.code == 200) this.$message.success(res.data.msg);
        else this.$message.error(res.data.code + "::" + res.data.msg);
      });
      this.dialogVisibleD = false; //购买之后关闭单独购买的dialog
      this.getCarts(); //购买之后重新获取购物车列表值
      this.$refs.multipleTable.clearSelection(); //清空之前批量删除选择的书籍
      this.cartId = ""; //把之前单独购买的id设置为''
      // console.log(this.multipleSelection);
    },
    async handleBuyP() {
      //批量购买
      //发送请求
      // console.log(this.addressId)
      await buyByIds(this.addressId, this.multipleSelection).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
      this.dialogVisible = false; //购买之后关闭dialog
      this.getCarts(); //购买之后之后重新获取购物车列表值
      this.$refs.multipleTable.clearSelection(); //清空之前批量选择的书籍
      console.log(this.multipleSelection);
    },

    async handleConfirm(id) {
      //单独点击删除按钮，下面有个点击批量删除按钮，注意一下多了个P
      // console.log(id)
      await deleteById(id).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
      this.getCarts(); //删除之后重新获取购物车列表值
      this.$refs.multipleTable.clearSelection(); //清空之前批量删除选择的书籍
      console.log(this.multipleSelection);
    },
    async handleConfirmP() {
      //点击批量删除并点击确定之后触发事件
      //在这里发送批量删除的接口
      await deleteByIds(this.multipleSelection).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
      this.getCarts(); //删除之后重新获取购物车列表值
      this.$refs.multipleTable.clearSelection(); //清空之前批量删除选择的书籍
      console.log(this.multipleSelection);
    },
    getCarts() {
      //用户点击我的购物车就去请求这个获取他自己所有的购物车信息
      getCartsById(localStorage.getItem("userId")).then((res) => {
        if (res.data.code == 200) {
          this.carts = res.data.data;
        }
      });
    },
    async getAddresses() {
      await getAddress(localStorage.getItem("userId")).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data.length != 0) {
            res.data.data.forEach((address) => {
              address.detailedAddress = address.detailedAddress.replace(
                /%\//g,
                ""
              );
            });
            this.address = res.data.data;
            this.addressId = res.data.data[0].id; //默认把地址第一条付给那个值
          }

          // console.log((res.data.data).id)
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
    },
    toggleSelection() {
      //取消选择的购物车
      console.log(this.multipleSelection);
      this.$refs.multipleTable.clearSelection();
    },
    handleSelectionChange(val) {
      //选择某一行或全部就添加进入multipleSelection
      // 假设 val 是一个数组，每个元素都是一个包含 id 字段的 JSON 对象
      // 使用 map 方法遍历 val 数组，并返回一个新的数组，该数组只包含 id 字段的值
      const ids = val.map((item) => item.id);
      // 假设 this.idArray 是你想要存储这些 id 的数组
      this.multipleSelection = ids; // 无需深拷贝，因为 id 是基本数据类型
      console.log(this.multipleSelection);
    },
  },

  mounted() {
    this.getCarts();
    //这里获取地址，要判断是否有地址，不存在就不能购买，详情界面也一样
    this.getAddresses();
  },
};
</script>

<style>
.el-card__body,
.el-main {
  padding-bottom: 0px !important;
}
</style>